import * as React from 'react';
import { View, StyleSheet, ViewProps } from 'react-native';

import { IS_TABLET_DEVICE, NOTCH_WIDTH, TABLET_WIDTH } from '../../constant';
import statusBarManager from '../../util/native/statusBarManager';
import { systemUtil } from '../../util/native';
import { getScreenInfo, ScreenOrientation } from '../../util/screen';

export enum NotchType {
  Top,
  Bottom,
  TopAndBottom,
  Left
}

interface Notch extends ViewProps {
  style?: any;
  children?: any;
  type?: NotchType;
}

const Notch = ({
  style = {},
  children,
  type = NotchType.Left,
  ...props
}: Notch): React.ReactElement => {
  const resStyle = StyleSheet.flatten(style);
  const resPaddingLeft =
    resStyle.paddingLeft || resStyle.paddingHorizontal || 0;
  let paddingLeft = Number(resPaddingLeft);
  const resPaddingTop = resStyle.paddingTop || resStyle.paddingVertical || 0;
  const resPaddingBottom =
    resStyle.paddingBottom || resStyle.paddingVertical || 0;
  let paddingTop = Number(resPaddingTop);
  let paddingBottom = Number(resPaddingBottom);

  const height = statusBarManager.getStatusBarHeight();

  const bottomSafeAreaHeight = systemUtil.getBottomSafeAreaHeight();

  if (type === NotchType.Left) {
    paddingLeft += Number(NOTCH_WIDTH);
  } else if (type === NotchType.Bottom && bottomSafeAreaHeight > 0) {
    paddingBottom += bottomSafeAreaHeight;
    paddingTop = 0;
  } else if (type === NotchType.Top) {
    paddingTop += Number(height);
    paddingBottom = 0;
  } else {
    paddingTop += Number(height);
    if (bottomSafeAreaHeight > 0) {
      paddingBottom += bottomSafeAreaHeight;
    }
  }

  const { width } = getScreenInfo({
    screenOrientation:
      type === NotchType.Left
        ? ScreenOrientation.Landscape
        : ScreenOrientation.Portrait
  });

  let screenWidth = width;
  if (type !== NotchType.Left) {
    screenWidth = IS_TABLET_DEVICE ? TABLET_WIDTH : width;
  }

  return (
    <View
      {...props}
      style={[
        style,
        type === NotchType.Left ? { paddingLeft } : {},
        type === NotchType.Top || type === NotchType.TopAndBottom
          ? { paddingTop }
          : {},
        type === NotchType.Bottom || type === NotchType.TopAndBottom
          ? { marginBottom: paddingBottom }
          : {},
        { width: screenWidth }
      ]}
    >
      {children}
    </View>
  );
};

export default Notch;
